<template>
  <xn-form-container
    :title="formData.ID ? '编辑角色信息' : '新增角色信息'"
    :width="500"
    :visible="visible"
    :destroy-on-close="true"
    @close="onClose"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <a-form-item label="角色名称" name="RoleName">
        <a-input
          v-model:value="formData.RoleName"
          placeholder="请输入角色名称"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="角色说明" name="RoleDesp">
        <a-input
          v-model:value="formData.RoleDesp"
          placeholder="角色说明"
          allow-clear
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button class="xn-mr8 mr10" @click="onClose">关闭</a-button>
      <a-button type="primary" @click="onSubmit">{{
        formData.ID ? "确认修改" : "确认新增"
      }}</a-button>
    </template>
  </xn-form-container>
</template>

<script setup>
import { required } from "@/utils/formRules";
import rolemgrApi from "@/api/systemManagement/rolemgrApi";

import { ref, onMounted, watch } from "vue";
import XnFormContainer from "@/components/XnFormContainer/index.vue";
import { message } from "ant-design-vue";

// 默认是关闭状态
const visible = ref(false);
const emit = defineEmits({ successful: null });
const formRef = ref();

// 表单数据
const formData = ref({
  RoleDesp: "",
});
// 打开抽屉
const onOpen = (record) => {
  visible.value = true;
  if (record) {
    formData.value = Object.assign({}, record);
  } else {
    formData.value = {};
  }
};
// 关闭抽屉
const onClose = () => {
  formRef.value.resetFields();
  visible.value = false;
};

// 默认要校验的
const formRules = {
  RoleName: [required("请输入角色名称")],
};

// 验证并提交数据
const onSubmit = () => {
  // 有id为编辑,无id为新增
  if (!formData.value.ID) {
    formRef.value
      .validate()
      .then(() => {
        rolemgrApi
          .addRole({
            RoleName: formData.value.RoleName,
            RoleDesp: formData.value.RoleDesp ? formData.value.RoleDesp : "",
          })
          .then(() => {
            message.success("新增成功");
            onClose();
            emit("successful");
          });
      })
      .catch(() => {});
    return;
  }
  formRef.value
    .validate()
    .then(() => {
      rolemgrApi
        .modifyRole({
          ID: formData.value.ID,
          RoleName: formData.value.RoleName,
          RoleDesp: formData.value.RoleDesp ? formData.value.RoleDesp : "",
        })
        .then(() => {
          message.success("修改成功");
          onClose();
          emit("successful");
        });
    })
    .catch(() => {});
};

// 调用这个函数将子组件的一些数据和方法暴露出去
defineExpose({
  onOpen,
});
</script>
